<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <!-- 注册的表单 -->
        <el-form
          class="login_form"
          :model="loginForm"
          :rules="rules"
          ref="loginForms"
        >
          <h1>Hello</h1>
          <h2>基于BP二手房房价预测与分析</h2>
          <el-form-item prop="username">
            <el-input
              :prefix-icon="User"
              v-model="loginForm.username"
              placeholder="请输入账号"
              style="height: 50px"
            ></el-input>
          </el-form-item>
          <el-form-item prop="email">
            <el-input
              :prefix-icon="User"
              v-model="loginForm.email"
              placeholder="请输入邮箱"
              style="height: 50px"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              :prefix-icon="Lock"
              v-model="loginForm.password"
              show-password
              placeholder="请输入密码"
              style="height: 50px"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              :prefix-icon="Lock"
              v-model="loginForm.password_confirm"
              show-password
              placeholder="请确认密码"
              style="height: 50px"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              :loading="loading"
              class="login_btn"
              type="primary"
              size="default"
              @click="register"
            >
              注册
            </el-button>
          </el-form-item>
          <el-form-item>
            <div class="link">
              <RouterLink to="/login">
                <el-link>已有账号？去登录</el-link>
              </RouterLink>
            </div>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
// 引入用户相关的小仓库
import useUserStore from '@/store/modules/user'
// 引入路由
import { useRouter, useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'
// 引入注册接口
import { reqRegister } from '@/api/user/index'

let useStore = useUserStore()
// 获取路由对象
let router = useRouter()
// 使用路由参数，使得点击登录后跳转到对应的路由
let route = useRoute()
//定义变量控制按钮加载效果
let loading = ref(false)
//获取el-form组件
let loginForms = ref()
//收集账号与密码的数据
let loginForm = reactive({
  username: '',
  email: '',
  password: '',
  password_confirm: '',
})

// 注册
const register = async () => {
  // 保证全部表单校验通过之后再发请求
  await loginForms.value.validate()
  loading.value = true
  // 1.点击注册
  // 2.调用注册函数业务逻辑
  // 3.请求成功=>跳转到登录页；登录失败=>提示错误信息
  // 保证注册成功
  let res = await reqRegister(loginForm)
  if (res.code === 201) {
    ElNotification({
      type: 'success',
      message: res.msg,
    })
    // 跳转到登录页面
    router.push('/login')
    //注册成功加载效果也消失
    loading.value = false
  } else {
    ElNotification({
      type: 'error',
      message: res.error_msg,
    })
    //注册失败加载效果也消失
    loading.value = false
  }
  // location.reload()
}
//自定义校验规则函数
const validatorUserName = (rule: any, value: any, callback: any) => {
  //rule:即为校验规则对象
  //value:即为表单元素文本内容
  //函数:如果符合条件callBack放行通过即为
  //如果不符合条件callBack方法,注入错误提示信息
  if (value.length >= 6 && value.length <= 18) {
    callback()
  } else {
    callback(new Error('账号长度为6-18位之间'))
  }
}
const validatorEmail = (rule: any, value: any, callback: any) => {
  let regExp = /^[1-9]{9,11}@(qq\.com|163\.com)$/
  if (regExp.test(value)) {
    callback()
  } else {
    callback(
      new Error('请输入符合要求的邮箱，例如：xxxx@qq.com 或 xxxx@163.com'),
    )
  }
}
const validatorPassword = (rule: any, value: any, callback: any) => {
  let regExp = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z0-9]{6,18}$/
  if (regExp.test(value)) {
    callback()
  } else {
    callback(new Error('密码必须包含至少1个字母和1个数字，且长度为6-18位'))
  }
}
const validatorPasswordConfirm = (rule: any, value: any, callback: any) => {
  if (value === '' || value === null) {
    callback(new Error('确认密码不能为空'))
  } else if (value !== loginForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback() // 校验成功
  }
}

//定义表单校验需要配置对象
const rules = {
  //规则对象属性:
  //required,代表这个字段务必要校验的
  //min:文本长度至少多少位
  //max:文本长度最多多少位
  //message:错误的提示信息
  //trigger:触发校验表单的时机 change->文本发生变化触发校验,blur:失去焦点的时候触发校验规则
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { trigger: 'change', validator: validatorUserName },
  ],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { trigger: 'change', validator: validatorEmail },
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { trigger: 'change', validator: validatorPassword },
  ],
  password_confirm: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    { trigger: 'change', validator: validatorPasswordConfirm },
  ],
}
</script>
<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/bg.jpg') no-repeat;
  background-size: cover;
  position: relative;

  .cover {
    width: fit-content;
    background-color: aliceblue;
    position: absolute;
    top: 110%;
    right: 7%;
    transform: translate(-50%, -50%);
    z-index: 1000;
  }

  .login_form {
    position: relative;
    top: 50%;
    right: 40%;
    width: 80%;
    // background: url('@/assets/images/login_form.png') no-repeat;
    // background-size: cover;
    background: rgba(243, 239, 239, 0.3);
    // background-color: rgba(232, 224, 224, 0.2);
    padding: 40px;
    h1 {
      color: #fff;
      font-size: 40px;
    }

    h2 {
      font-size: 20px;
      color: #fff;
      margin: 20px 0px;
    }
    .link {
      font-size: 15px;
      color: #fff;
    }
    .link:hover {
      color: #0c24da;
    }

    .login_btn {
      width: 100%;
    }
  }
}
</style>
